import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from 'element-plus'
import {
  invoiceListApi,
  invoiceStoreApi,
  invoiceUpdateApi,
  invoiceDeleteApi,
  invoiceShowApi,
} from "@/api/invoiceApi";
import {
  projectSelectApi
} from "@/api/projectApi";
export function useCorps() {
  const form = reactive({
    page: 1,
    perPage: 20,
    name: "",

  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    background: true,
    pageSizes: [10,20,50,100]
  });
  const columns: TableColumnList = [
    {
      label: "ID",
      prop: "invoiceId",
      width: 60
    },
    {
      label: "所属项目",
      prop: "project.projectName"
    },
    {
      label: "任务阶段",
      prop: "taskName",
      slot: "taskName"
    },
    // {
    //   label: "增值税",
    //   prop: "isVat",
    //   formatter:(row: any)=> {
    //     return row.isVat === 1?'是':'否';
    //   }
    // },
    {
      label: "抬头名称",
      prop: "title"
    },
    // {
    //   label: "抬头内容",
    //   prop: "content"
    // },
    {
      label: "金额",
      prop: "amount",
    },
    // {
    //   label: "税号",
    //   prop: "taxNo",
    // },
    // {
    //   label: "税金",
    //   prop: "tax",
    // },
    // {
    //   label: "公司名称",
    //   prop: "companyName"
    // },
    // {
    //   label: "公司地址",
    //   prop: "companyAddress"
    // },
    // {
    //   label: "联系电话",
    //   prop: "telephone"
    // },
    // {
    //   label: "开户银行",
    //   prop: "bankName"
    // },
    // {
    //   label: "银行帐号",
    //   prop: "bankAccount"
    // },
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
      width: 140
    }
  ];
  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    onSearch()
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
    onSearch()
  }

  async function onSearch() {
    loading.value = true;
    const { result } = await invoiceListApi(toRaw(form));
    dataList.value = result.list;
    pagination.total = result.total;
    pagination.pageSize = result.perPage*1;
    pagination.currentPage = result.page*1;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  const formInline = ref();
  async function openDialog(title = "创建发票", row?: FormItemProps) {

    const res = await projectSelectApi({type: 'all'})
    let formInline = {
      title: title,
      projectSelect: res?.result ?? [],
      invoiceId: row?.invoiceId ?? "",
      invoiceTitle: row?.title ?? null,
      amount: row?.amount ?? null,
      projectId: row?.project?.id ?? null,
      projectName: row?.project?.name ?? '--',
      taskId: []
    };
    if (`${title}` === "创建发票") {

    } else {
      const { result } = await invoiceShowApi({ invoiceId: row.invoiceId });
      let taskIds = []
      if(result?.tasks && result?.tasks?.length > 0) {
        for (let item of result.tasks) {
          taskIds.push(item.taskId)
        }
      }
      formInline.taskId = taskIds
    }

    addDialog({
      title: `${title}`,
      props: {
        formInline: formInline
      },
      top: '5%',
      width: "500px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;

        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          done();
          onSearch();
        }

        FormRef.validate(valid => {
          if (valid) {
            let params = {
              invoiceId: curData.invoiceId,
              // isVat: curData.isVat,
              // title: curData.invoiceTitle,
              // content: curData.content,
              // amount: curData.amount.toFixed(2),
              // taxNo: curData.taxNo,
              // tax: curData.tax.toFixed(2),
              // companyName: curData.companyName,
              // companyAddress: curData.companyAddress,
              // telephone: curData.telephone,
              // bankName: curData.bankName,
              // bankAccount: curData.bankAccount,
              title: curData.invoiceTitle,
              taskIds: curData.taskId,
              amount: curData.amount.toFixed(2),
              projectId: curData.projectId
            }
            if (title === "创建发票") {
              invoiceStoreApi(toRaw(params)).then((res) => {
                if(res?.code === 200) {
                  chores();
                }
              })
              .catch(error => {
                message(error.response.data.msg ?? "操作失败,请联系管理员", {
                  type: "error"
                });
              });
            } else {
              invoiceUpdateApi(params).then((res) => {
                if(res?.code === 200) {
                  chores();
                }
              })
              .catch(error => {
                message(error.response.data.msg ?? "操作失败,请联系管理员", {
                  type: "error"
                });
              });
            }
          }
        });
      }
    });
  }
  onMounted(async () => {
    onSearch();

  });

  function handleDelete(row) {
    ElMessageBox.confirm('请继续进行删除操作?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    .then(() => {
      invoiceDeleteApi({ invoiceId: row.invoiceId }).then((res) => {
        if(res?.code === 200) {
          message(`删除成功`, { type: "success" });
          onSearch();
        }
      });
    })
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete,
  };
}
